package com.stop.activity.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.stop.R;
import com.stop.activity.adapter.PlayersArrayAdapter;
import com.stop.controller.StopController;

public class SalaPlayersActivity extends Fragment {

	private PlayersArrayAdapter adapterJogadores = null;
	
	private ListView list = null;
	
	private View view = null;
	
	private JSONObject salaResumed;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = (LinearLayout) inflater.inflate(R.layout.activity_info_sala_fragment_players, container, false);
		
		list = (ListView) view.findViewById(R.id.salaPlayers);
		
		adapterJogadores = new PlayersArrayAdapter(view.getContext(), R.layout.activity_info_sala_fragment_players_adapter, new ArrayList<String>());
		
		list.setAdapter(adapterJogadores);
		
		try{
			salaResumed = new JSONObject(this.getArguments().getString("sala"));
			
			new AtualizarPlayers().execute();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return view;
	}
	
	class AtualizarPlayers extends AsyncTask<Void, Void, Void> {

		private JSONObject sala = null;
		
		protected Void doInBackground(Void... params) {
			
			try {
				JSONObject response = StopController.getInstancia().entrarSala(salaResumed.getString("uid"), "players");
				
				if(!response.getBoolean("error")){
					this.sala = response.getJSONObject("sala");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return null;
		}
		
		protected void onPostExecute(Void result) {
			if(this.sala != null){
				try{
					JSONArray jogadores = sala.getJSONArray("jogadores");
					
					List<String> arrayJogadores = new ArrayList<String>();
					for (int i = 0; i < jogadores.length(); i++) {
						final String jogador = jogadores.getString(i);
						arrayJogadores.add(jogador);
					}
					
					adapterJogadores.clear();
					adapterJogadores.addAll(arrayJogadores);
					adapterJogadores.notifyDataSetChanged();
					
					if(!isHidden() && !isDetached() && isInLayout()){
						new Thread(){
							public void run() {
								try {
									Thread.sleep(5000);
									new AtualizarPlayers().execute();
								} catch (InterruptedException e) {	}
							};
						}.start();
					}
					
				}catch(Exception e){
					e.printStackTrace();
				}
			}			
		}
		
	}
	
}